package com.xiaohong.oauth.controller;


import com.xiaohong.oauth.service.UserLoginService;
import com.xiaohong.user.feign.UserFeign;
import com.xiaohong.user.pojo.LoginUser;
import com.xiaohong.user.pojo.User;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class userLoginController {

    //客户端id
    @Value("${auth.clientId}")
    private String clientId;

    //客户端密钥
    @Value("${auth.clientSecret}")
    private String clientSecret;

    @Autowired
    private UserLoginService userLoginService;

    @Autowired
    private UserFeign userFeign;

    /**
     * 参数传递:
     * 1.账号 username=szitheima
     * 2.密码 password=szitheima
     * 3.授权方式 grant_type=password
     * 请求头传递
     * 4. Basic Base64(客户端ID:客户端秘钥) Authorization=Basic Y2hhbmdnb3U6Y2hhbmdnb3U=
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginUser loginUser, HttpServletRequest request) throws Exception {
        //获取用户登录IP地址
        String ip = request.getHeader("ip");

        if (loginUser.getAgree() != null && !loginUser.getAgree()){
            return new Result(false, StatusCode.PARAMETERERROR,"登录失败,未勾选用户协议和隐私条款！");
        }
        String grant_type = "password";
        try {
            ResponseEntity<Map> entity = userLoginService.login(loginUser.getPhone(), loginUser.getPassword(), grant_type, clientId, clientSecret);
            if (entity.getBody() != null){
                // 更新用户最后登录ip和最后登录时间
                User user1 = new User();
                user1.setPhone(loginUser.getPhone());
                User user2 = userFeign.findList(user1).getData().get(0);
                user2.setLastLoginIP(ip);
                user2.setLastLoginTime(new Date());
                // 注意！！这里不能把查询到的数据全部更新进去，因为例如乐观锁·创建时间·更新时间是自动填充的，不能手动输入
                // 解决方法：在创建一个user用来更新，由于是根据id更新，所以只需要把要修改的部分和id填进去即可
                User user = new User();
                user.setLastLoginIP(ip);
                user.setLastLoginTime(new Date());
                user.setId(user2.getId());
                userFeign.update(user);

                return new Result(true, StatusCode.OK,"登录成功！",entity);
            }
            return new Result(false, StatusCode.LOGINERROR,"登录失败！",entity);
        }catch (NullPointerException ne){
            return new Result(true, StatusCode.UNSTART,"服务未启动！");
        }catch (HttpClientErrorException.BadRequest badRequest){
            return new Result(true, StatusCode.PARAMETERERROR,"用户名或密码错误！");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(true, StatusCode.PARAMETERERROR,"服务器内部错误！");
        }
    }

    @PostMapping("/refresh")
    public Result refresh(String refresh_token) throws Exception {
        String grant_type = "refresh_token";
        try {
            ResponseEntity<Map> entity = userLoginService.refresh( grant_type, refresh_token,clientId,clientSecret);
            if (entity.getBody() != null){
                return new Result(true, StatusCode.OK,"刷新令牌成功！",entity);
            }
            return new Result(false, StatusCode.LOGINERROR,"刷新令牌失败！",entity);
        }catch (NullPointerException ne){
            return new Result(true, StatusCode.REPERROR,"服务未启动！");
        }
    }

}
